#include <fileOpt.h>

int fileOptReadAll(const char *filename, struct cstring *outstr)
{
    if(!outstr)
    {
        logerror("outstr error");
        return -1;
    }
    FILE *tmpFd = fopen(filename, "r");
    if(!tmpFd)
    {
        logerror("open error %s", filename);
        return -1;
    }
    fseek(tmpFd, 0, SEEK_END);
    long tmpsize = ftell(tmpFd);
    if(tmpsize > 10 * 1024 * 1024)
    {
        logerror("size too big: %ld", tmpsize);
        return -1;
    }
    fseek(tmpFd, 0, SEEK_SET);
    cstrResize(outstr, tmpsize);
    tmpsize = fread(outstr->str, outstr->size, 1, tmpFd);
    fclose(tmpFd);
    return tmpsize;
}

int fileOptWrite(const char *filename, const struct cstring *instr)
{
    if(!instr)
    {
        logerror("outstr error");
        return -1;
    }
    FILE *tmpFd = fopen(filename, "w+");
    if(!tmpFd)
    {
        logerror("open error %s", filename);
        return -1;
    }
    int tmpsize = fwrite(instr->str, instr->size, 1, tmpFd);
    fclose(tmpFd);
    return tmpsize;
}
